<template>
  <div>
    <el-card shadow="never">
      <div id="auto-archive">
        <el-radio v-model="archiveType" label="1" class="archiveTypeStyle">自动归档</el-radio>
        <transition name="el-fade-in-linear">
          <el-form v-show=" archiveType=='1' " ref="autosend" :inline="true" :model="autoArchive" class="demo-form-inline" style="margin-top: 20px" label-width="130px">
            <el-form-item label="设置时间">
              <el-select v-model="autoArchive.setTime" placeholder="归档天数" clearable @change="autoArchive.advanceTime>parseInt(autoArchive.setTime) ? autoArchive.advanceTime=parseInt(autoArchive.setTime) : '' ">
                <el-option label="0天" value="0" />
                <el-option label="30天" value="30" />
                <el-option label="90天" value="90" />
                <el-option label="180天" value="180" />
                <el-option label="365天" value="365" />
              </el-select>
            </el-form-item>
            <el-form-item label="归档前是否通知">
              <el-radio-group v-model="autoArchive.inform" @change="autoArchive.inform=='2' ? autoArchive.advanceTime=0 : ''">
                <el-radio label="1">是</el-radio>
                <el-radio label="2">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-show="autoArchive.inform==1" label="提前通知">
              <el-input-number v-model="autoArchive.advanceTime" :controls="false" :min="0" :max="parseInt(autoArchive.setTime)" :disabled="!autoArchive.setTime" />（天）
            </el-form-item>
            <el-form-item class="fr">
              <el-button type="primary" @click="autoSave()">保存</el-button>
            </el-form-item>
          </el-form>
        </transition>
      </div>
    </el-card>

    <!-- <el-divider /> -->
    <el-card shadow="never">
      <el-radio v-model="archiveType" label="2" class="archiveTypeStyle" @change="clearAuto()">手动归档</el-radio>
      <transition name="el-fade-in-linear">
        <div v-show="archiveType==2" style="margin-top: 20px">
          <el-form ref="send" :model="send" class="elform" style="width: 100%;border-bottom: 1px solid #F0F0EE;overflow: auto">
            <el-row style="margin-left: 30px;">
              <el-col :span="3">
                <el-form-item label="任务类别:" prop="taskgories">
                  <el-select v-model="send.taskgories" style="width:60%;" filterable @change="send.medication = ''">
                    <el-option-group v-for="(group,index) in taskgortion" :key="group.label+index" :label="group.label">
                      <el-option v-for="(item,index2) in group.options" :key="item.value+index2" :label="item.label" :value="item.value" />
                    </el-option-group>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-form-item label="病历状态:" prop="medication">
                  <el-select v-if="send.taskgories == '分诊'" v-model="send.medication" style="width:60%;" filterable>
                    <el-option v-for="item in medicalconditionTriage" :key="item.value" :value="item.value" :label="item.label" />
                  </el-select>
                  <el-select v-else v-model="send.medication" style="width:60%;" filterable>
                    <el-option v-for="item in medicalcondition" :key="item.value" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4">
                <el-form-item label="时间范围:" prop="startimes">
                  <el-date-picker
                    v-model="send.startimes"
                    type="datetime"
                    style="width:72%"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :clearable="false"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="4" style="margin-left: 5px">
                <el-form-item label="至" prop="endtime">
                  <el-date-picker
                    v-model="send.endtime"
                    type="datetime"
                    style="width: 72%"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    :clearable="false"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="年龄段:" prop="starage"><el-input v-model="send.starage" style="width:50%" /></el-form-item>
              </el-col>
              <el-col :span="2">
                <el-form-item label="至" prop="eddage">
                  <el-input v-model="send.eddage" style="width:50%" />
                  岁
                </el-form-item>
              </el-col>
              <el-col :span="3">
                <el-button type="primary" @click="resetPage();search()">搜索</el-button>
                <el-button @click="reset()">重置</el-button>
              </el-col>
              <el-col :span="2" style="text-align: right">
                <el-button type="primary" @click="outcome()">转归</el-button>
              </el-col>
            </el-row>
          </el-form>
          <el-row>
            <el-col style="padding: 20px;">
              <el-table
                ref="multipleTable"
                v-loading="loading"
                :data="tableData"
                height="670"
                style="width: 100%; "
                class="table"
                border
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="50" header-align="center" align="center" />
                <el-table-column label="任务类别" min-width="150" prop="diseaseType" header-align="center" align="center" />
                <el-table-column prop="createTime" label="建挡时间" min-width="150" header-align="center" align="center" />
                <el-table-column prop="id" label="患者编号" min-width="150" header-align="center" align="center" />
                <el-table-column prop="name" label="患者姓名" min-width="150" header-align="center" align="center" />
                <el-table-column prop="sex" label="性别" min-width="150" header-align="center" align="center" />
                <el-table-column prop="age" label="年龄" min-width="150" header-align="center" align="center" />
                <el-table-column label="任务状态" min-width="150" header-align="center" align="center" :formatter="forcondition" />
                <el-table-column label="查看" min-width="150" header-align="center" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" @click="jumpsee(scope.row)">跳转查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                style="float: right"
                :current-page="currentPage"
                :page-sizes="[10, 20]"
                :page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageTotal"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-col>
          </el-row>
        </div>
      </transition>
    </el-card>
  </div>
</template>
<script>
import { saveList, selectList, saveAutoArchives, selectAutoArchives, cancleAutoArchives } from '@/api/back-management/Archive_Setting'

import format from '@/utils/format'
export default {
  name: 'ArchiveSetting',
  data() {
    return {
      send: {
        startimes: '',
        // startimes: new Date(new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + ' 23' + ':' + '59' + ':' + '59'),
        endtime: new Date(new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + ' 23' + ':' + '59' + ':' + '59'),
        taskgories: '绿道',
        starage: '',
        eddage: '',
        medication: ''
      },
      medicalcondition: [{ value: '', label: '全部' }, { value: '急救中', label: '急救中' }, { value: '1', label: '已上报' }, { value: '0', label: '未上报' }],
      medicalconditionTriage: [{ value: '', label: '全部' }, { value: '-2', label: '分诊中' }, { value: '0', label: '分诊完成' }],
      taskgortion: [
        {
          label: '',
          options: [{ value: '绿道', label: '全部' }, { value: '胸痛', label: '胸痛' }, { value: '卒中', label: '卒中' }]
        },
        {
          label: '',
          options: [{ value: '分诊', label: '分诊' }]
        }
      ],
      // taskgortion0: [
      //   { value: '绿道', label: '全部' },
      //   { value: '胸痛', label: '胸痛' },
      //   { value: '卒中', label: '卒中' },
      //   { value: '分诊', label: '分诊' }
      // ],
      tableData: [],
      archiveType: '1',
      /* 表格分页参数*/
      currentPage: 1,
      pagesize: 10,
      pageTotal: 0,
      userId: this.$store.getters.userId,
      tablelist: [],
      loading: true,
      medicts: true,
      autoArchive: {
        id: null, // id（int）没有为新增传null，有为更新；
        greenType: '绿道',
        hospitalId: this.$store.getters.hospitalId,
        userId: this.$store.getters.userId,
        advanceTime: '0', // （提前几天通知，string）"
        setTime: '', // (自动归档的设置时间，string);
        inform: '' // 归档前是否通知
      }
    }
  },
  created() {
    this.selectAuto()
    if (new Date().getMonth() === 0) {
      this.send.startimes = new Date((new Date().getFullYear() - 1) + '-' + 12 + '-' + new Date().getDate() + ' 00' + ':' + '00' + ':' + '00')
    } else {
      this.send.startimes = new Date(new Date().getFullYear() + '-' + new Date().getMonth() + '-' + new Date().getDate() + ' 00' + ':' + '00' + ':' + '00')
    }
    this.search()
  },
  methods: {
    clearAuto() {
      const data = {
        id: parseInt(this.autoArchive.id) || ''
      }
      cancleAutoArchives(data).then(res => {
        console.log(data)
        this.autoArchive = {
          id: null, // id（int）没有为新增传null，有为更新；
          greenType: '绿道',
          hospitalId: this.$store.getters.hospitalId,
          userId: this.$store.getters.userId,
          advanceTime: '0', // （提前几天通知，string）"
          setTime: '', // (自动归档的设置时间，string);
          inform: '' // 归档前是否通知
        }
        this.$message.info('自动归档任务已取消')
      })
    },
    selectAuto() {
      const data = {
        hospitalId: this.autoArchive.hospitalId,
        greenType: this.autoArchive.greenType
      }
      console.log('res------', data)
      selectAutoArchives(data).then(res => {
        const ele = res.data[0]
        if (ele) {
          this.autoArchive = {
            id: ele.id, // id（int）没有为新增传null，有为更新；
            greenType: '绿道',
            hospitalId: this.$store.getters.hospitalId,
            userId: this.$store.getters.userId,
            setTime: ele.setTime, // (自动归档的设置时间，string);
            advanceTime: ele.advanceTime, // （提前几天通知，string）"
            inform: parseInt(ele.advanceTime) > 0 ? '1' : '2' // 归档前是否通知
          }
          this.archiveType = '1' // 选中"自动归档"选项
        } else {
          this.archiveType = '2' // 选中"手动归档"选项
        }
      })
    },
    autoSave() {
      const data = {
        id: parseInt(this.autoArchive.id),
        greenType: this.autoArchive.greenType,
        hospitalId: parseInt(this.autoArchive.hospitalId),
        userId: parseInt(this.autoArchive.userId),
        advanceTime: this.autoArchive.advanceTime,
        setTime: this.autoArchive.setTime
      }
      saveAutoArchives(data).then(res => {
        if (res.code !== 9999) {
          this.selectAuto()
          this.$message.success('保存成功')
        }
      })
    },
    /* 格式化数据*/
    forcondition(row) {
      let str = ''
      if (row.isOpen.toString() === '1') {
        str += '急救中 '
      }
      if (row.diseaseType === '胸痛') {
        if (row.isUploadChinacpc > '0') {
          str += '已上报 '
        } else {
          str += '未上报 '
        }
      } else if (row.diseaseType === '卒中') {
        if (row.isUploadChinaais > '0') {
          str += '已上报 '
        } else {
          str += '未上报 '
        }
      }
      return str
    },
    handleSelectionChange(row) {
      this.tablelist = []
      for (let i = 0; i < row.length; i++) {
        const obj = {}
        obj.id = row[i].id
        this.tablelist.push(obj)
      }
    },
    resetPage() {
      this.currentPage = 1
      this.pagesize = 10
      this.pageTotal = 0
    },

    /* 搜索*/
    search() {
      this.loading = true
      // if (this.send.taskgories != '') {
      // this.medicts = false
      // } else if (this.send.taskgories == '') {
      // this.medicts = true
      //   this.send.medication = ''
      // }
      /* 单选框改变*/
      const data = {}
      data.pageNum = this.currentPage
      data.pageSize = this.pagesize
      data.diseaseType = this.send.taskgories
      data.userId = this.userId

      if (this.send.taskgories === '分诊') {
        data.isOpen = this.send.medication
        data.isUpload = ''
      } else {
        // if (this.send.medication === '1') {
        //   data.isOpen = this.send.medication
        //   data.isUpload = ''
        // }
        if (this.send.medication === '急救中') {
          data.isOpen = '1'
          data.isUpload = ''
        } else {
          data.isOpen = ''
          data.isUpload = this.send.medication
        }
      }
      data.startTime = format(this.send.startimes, 'YYYY-MM-DD HH:mm:ss')
      data.endTime = format(this.send.endtime, 'YYYY-MM-DD HH:mm:ss')
      data.startAge = this.send.starage
      data.endAge = this.send.eddage

      // console.log(1111, data)
      // this.loading = false
      // return false
      selectList(data).then(res => {
        this.tableData = res.data.list
        this.pageTotal = res.data.total
        this.loading = false
      })
    },
    /* 重置*/
    reset() {
      this.$refs['send'].resetFields()
      this.medicts = true
      this.search()
    },
    /* 转归*/
    outcome() {
      if (this.tablelist.length === 0) {
        this.$message.warning('请至少选择一条')
        return false
      }
      const data = {
        archiveSettingsModelList: this.tablelist
      }
      saveList(data).then(res => {
        if (res.code === 9999) {
          this.$message({
            type: 'error',
            message: '转归失败!'
          })
        } else {
          this.$message({
            type: 'success',
            message: '转归成功!'
          })
          this.search()
        }
      })
    },
    /* 跳转查看*/
    jumpsee(row) {
      row.patientId = row.pid
      row.sourcePage = 'ArchiveSetting'
      this.$router.push({
        name: 'patientsList',
        params: row
      })
    },
    // 分页尺寸改变
    handleSizeChange(size) {
      this.pagesize = size
      this.search()
    },
    // 分页换页
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.search()
    }
  }
}
</script>

  <style scoped>
  .table /deep/ th:first-child .cell,
  .el-table--border td:first-child .cell {
    padding-left: 7px;
  }
  .archiveTypeStyle >>> .el-radio__label{
    font-size: 20px;
  }
  </style>
